import path from 'path';
import { writeFile } from 'node:fs/promises';
import { normalizePath, loadEnv } from 'vite';

function getOptions(options) {
  const opt = {
    __dirname: undefined,
    verbose: false,
    mode: undefined,
    envPrefix: 'VUE_APP_',
    defaultEnvDir: 'node_modules/@gis/lib/',
  };
  return Object.assign(opt, options);
}

function getDefaultEnvDir(__dirname, dir) {
  if (path.isAbsolute(dir)) {
    return normalizePath(dir);
  }
  return normalizePath(path.resolve(__dirname, dir));
}

function getEnv(options) {
  try {
    options = getOptions(options);
    const { __dirname, mode, envPrefix, defaultEnvDir } = options;
    const presetEnv = loadEnv(mode, getDefaultEnvDir(__dirname, defaultEnvDir), envPrefix);
    const currentEnv = loadEnv(mode, normalizePath(__dirname), envPrefix);
    const env = Object.assign({}, presetEnv, currentEnv);
    env.MODE = mode;
    env.DEV = mode === 'development';
    env.PROD = mode !== 'development';
    env.ENV_PREFIX = envPrefix;
    env.PROJECT_NAME = __dirname.split(/[\/\\]/g).slice(-1)[0];
    return env;
  } catch (e) {
    console.log('getEnv error: ', e);
    return {};
  }
}

function VitePluginEnv(options) {
  options = getOptions(options);
  return {
    name: 'vite:plugin-env',
    options: async (config) => {
      // console.log('options hook,config: ', config);
      try {
        const { __dirname, verbose } = options;
        const env = getEnv(options);
        const envJsonPath = normalizePath(path.resolve(__dirname, 'node_modules/@gis/lib/env.json'));
        await writeFile(envJsonPath, JSON.stringify(env), { encoding: 'utf8' });
        if (verbose !== false) {
          console.log(env);
        }
      } catch (e) {
        console.error('VitePluginEnv error: ', e);
      }
    },
  };
}

export { VitePluginEnv, getEnv };
